﻿using CommonLib;
using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleAppConsumer2;

internal class TestDeadQueue
{
    private static readonly string deadExchange = "dead_exchange";
    private static readonly string deadlQueue = "dead_queue";

    public static void TestTTL()
    {
        // 声明信道 channel
        var channel = RabbitMQUtil.CreateChannel();

        // 声明私信交换机
        channel.ExchangeDeclare(deadExchange, "direct");

        // 声明队列
        channel.QueueDeclare(deadlQueue, false, false, false, null);

        // 绑定队列和交换机
        channel.QueueBind(deadlQueue, deadExchange, "lisi");

        // 3 声明回调方法
        var consumer = new AsyncEventingBasicConsumer(channel);
        consumer.Received += Consumer_Received;
        async Task Consumer_Received(object sender, BasicDeliverEventArgs @event)
        {
            //Console.WriteLine(sender);
            //var channel = sender as IModel;
            try
            {
                var body = @event.Body.ToArray();
                var msg = Encoding.UTF8.GetString(body);
                Console.WriteLine("Consumer2 收到了死信消息" + msg);
                channel?.BasicAck(@event.DeliveryTag, false);
                await Task.Delay(1000);
            }
            catch (Exception ex)
            {
                channel?.BasicReject(@event.DeliveryTag, true);
                Console.WriteLine("处理消息：" + ex.Message);
            }
        }

        Console.WriteLine("Consumer2 等待接受死信队列消息");
        // 4 消费消息
        channel.BasicConsume(queue: deadlQueue, autoAck: false, consumer: consumer);
        Console.ReadLine();
    }

}
